
//mui初始化
mui.init({
    swipeBack: true //启用右滑关闭功能
});
var subpages = [pageName.home, pageName.merchant, pageName.mine, pageName.more];
var subpage_style = { top: '0px', bottom: '55px', zindex: 0 };

//创建子页面，首个选项卡页面显示，其它均隐藏；
mui.plusReady(function () {
    var sub = plus.webview.create(pageName.home, pageName.home, subpage_style);
    plus.webview.currentWebview().append(sub);
    // 关闭启动页
    plus.navigator.closeSplashscreen();
    // 清除上次启动无用缓存
    clearStoreage();
});
//当前激活选项
var activeTab = subpages[0];

//选项卡点击事件
mui('#footer').on('tap', 'a', function (e) {
    var targetTab = $(this).attr('href');
    if (targetTab == activeTab) { return; }

    // 扫描二维码
    if ($(this).hasClass("mid-ma")) { clicked(pageName.scanbarcode, true, true); return; }

    // 如果为主页面清空页面
    if (targetTab == pageName.home) {
        gohome();
    }

    var targepage = plus.webview.getWebviewById(targetTab);
    if (!targepage) {
        var sub = plus.webview.create(targetTab, targetTab, subpage_style);
        plus.webview.getWebviewById(pageName.main).append(sub);
    }
    if (targepage && targetTab == pageName.merchant) {
        plus.webview.getWebviewById(pageName.merchant).evalJS("receiveMainEvent()");
    }

    // 设置选中状态
    setSelectBackgroud($("#footer ul li a[href='" + activeTab + "']"), false);
    setSelectBackgroud($(this), true);

    //显示目标选项卡
    plus.webview.show(targetTab);
    //隐藏当前;
    plus.webview.hide(activeTab);
    //更改当前活跃的选项卡
    activeTab = targetTab;
});

// 返回主页关闭其他页
function gohome() {
    var allwebview = plus.webview.all();
    var mainview = plus.webview.getWebviewById(pageName.main);
    for (var i = 0; i < allwebview.length; i++) {
        var vie = allwebview[i];
        if (subpages.indexOf(vie.id) > -1 || mainview.id == vie.id || pageName.city == vie.id) {
            // TODO
        } else {
            console.log("关闭" + vie.id);
            vie.close("none");
        }
    }
}

function clear(pagename) {
    var allwebview = plus.webview.all();
    var mainview = plus.webview.getWebviewById(pageName.main);
    for (var i = 0; i < allwebview.length; i++) {
        var vie = allwebview[i];
        if (subpages.indexOf(vie.id) > -1 || mainview.id == vie.id || pagename == vie.id || pageName.city == vie.id) {
            // TODO
        } else {
            console.log("关闭" + vie.id);
            vie.close("none");
        }
    }
}

function setSelectBackgroud(tab, isselected) {
    var tip = tab.attr("tip");
    var item = "";
    switch (tip) {
        case "0":
            item = (isselected ? "<i class=\"icon iconfont icon-home\" style=\"font-size:2.0em; color:#f63;\"></i> <span style=\"color:#f63\">首页</span>" : "<i class=\"icon iconfont icon-home\" style=\"font-size:2.0em;\"></i> <span>首页</span>"); break;
        case "1":
            item = (isselected ? "<i class=\"icon iconfont icon-shopping\" style=\"font-size:2.0em; color:#f63;\"></i> <span style='color:#ff6633'>商家</span>" : "<i class=\"icon iconfont icon-shopping\" style=\"font-size:2.0em;\"></i> <span>商家</span>"); break;
        case "3":
            item = (isselected ? "<i class=\"icon iconfont icon-my\" style=\"font-size:2.0em; color:#f63;\"></i> <span style='color:#ff6633'>我的</span>" : "<i class=\"icon iconfont icon-my\" style=\"font-size:2.0em;\"></i> <span>我的</span>"); break;
        case "4":
            item = (isselected ? "<i class=\"icon iconfont icon-add\" style=\"font-size:2.0em; color:#f63;\"></i> <span style='color:#ff6633'>更多</span>" : "<i class=\"icon iconfont icon-add\" style=\"font-size:2.0em;\"></i> <span>更多</span>"); break;
        default: break;
    }

    tab.html(item);
}


// 扫描二维码
function scaned(t, r, f) {
    console.log("扫描结果：" + r);
    if (!r) { return; }

    // 订单号
    var orderid = getUrlParam("order", r);
    // 获取用户Code
    var scancode = getUrlParam("code", r); //"3EDF" ;
    // 是否用户二维码
    var isInvitebarcodeType = (r.toLowerCase().indexOf("register") >= 0 && (scancode && scancode.trim() != ""));
    // 是否订单二维码
    var isOrderbarcodeType = (r.toLowerCase().indexOf("done.html") >= 0 && (orderid && orderid.trim() != ""));

    // 根据Code获取用信息
    var scanuser = null;
    if (isInvitebarcodeType) {
        $.ajax({
            type: "GET", url: configManager.RequstUrl + "api/user/profile?code=" + scancode,
            async: false
        }).done(function (data) {
            if ("success" != data.state) { console.log(data.message); }
            scanuser = data.data;
        });
        if (!scanuser) { plus.nativeUI.alert("不存在该用户！"); return; }
    }

    // 当前登录用户（空表示未登录）
    var currentloginuser = JSON.parse(plus.storage.getItem(storageManager.user));

    // 是否用户二维码
    if (isInvitebarcodeType) {
        // 登录跳转支付/未登录跳转注册
        if (currentloginuser) {
            // 用户自己二维码不允许扫描
            if (currentloginuser.code == scanuser.code) { plus.nativeUI.alert("用户不允许扫描自己的二维码！"); return; }
            var param = "code=" + scancode;
            plus.webview.open("../../view/payment/direct.html?" + param, "../../view/payment/direct.html", {}, "zoom-out", 100, {});
        } else {
            var param = "type=" + scanuser.user_type + "&code=" + scancode;
            plus.webview.open("../../view/account/register.html?" + param, "../../view/account/register.html", {}, "zoom-out", 100, {});
        }
    } else if (isOrderbarcodeType) {
        // 只有商家才可以扫描订单码
        // 用户类型 1：普通用户； 2：商家； 3：商家子账号； 4：代理； 5：代理子账号； 6：后台管理人员
        if (currentloginuser && [2, 3].indexOf(currentloginuser.user_type) == -1) {
            plus.nativeUI.alert("对不起，您不是商家不可扫描！"); return;
        }

        // 登录跳转到订单二维码/未登录跳转到登录
        if (currentloginuser) {
            var param = "id=" + orderid;
            plus.webview.open("../../view/mine/order/confirmorder.html?" + param, "../../view/mine/order/confirmorder.html", {}, "zoom-out", 100, {});
        } else {
            // 跳转到登录
            plus.webview.open("../../view/account/login.html", "../../view/account/login.html", {}, "slide-in-bottom", 100, {});
        }
    } else {
        // 判断是否有效的URL
        var expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
        var objExp = new RegExp(expression);
        if (objExp.test(r) == true) {
            plus.runtime.openURL(r);
        } else {
            plus.nativeUI.alert("无效链接！");
        }
    }
}

// 跳转
function redirect(footid) {
    var dd = document.getElementById(footid)
    mui.trigger(dd, 'tap');
}

// 清除之前无用缓存
function clearStoreage() {
    plus.storage.removeItem(storageManager.searchtext);
}
